<template>
  <view class="address-form-page">
    <form @submit="saveAddress">
      <view class="form-group">
        <text class="label">联系人</text>
        <input v-model="form.name" class="input-field" placeholder="请输入姓名" />
      </view>
      <view class="form-group">
        <text class="label">手机号</text>
        <input v-model="form.phone" type="number" class="input-field" placeholder="请输入手机号" />
      </view>
      <view class="form-group">
        <text class="label">所在地区</text>
        <input v-model="form.area" class="input-field" placeholder="省、市、区" />
      </view>
      <view class="form-group">
        <text class="label">详细地址</text>
        <textarea v-model="form.details" class="input-field textarea-field" placeholder="街道、楼牌号等" auto-height />
      </view>
      
      <button form-type="submit" class="save-btn" :style="{ marginTop: '60rpx' }">保存</button>
    </form>
  </view>
</template>

      
<script setup>
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { request } from '@/utils/request.js';

// ---- Reactive State ----
const form = reactive({ id: null, name: '', phone: '', area: '', details: '' });
const isEditMode = ref(false);
const pageTitle = ref('');

// ---- API Methods ----

/**
 * @description 获取当前用户的姓名和手机号用于预填
 */
const fetchUserInfoForForm = async () => {
  try {
    const userId = uni.getStorageSync('userId');
    const data = await request({
      url: '/my/getInfo',
      method: 'POST',
      data: { userId: userId }
    });
    // API返回的是数组，取第一个
    if (data && data.length > 0) {
      form.name = data[0].userName;
      form.phone = data[0].userPhone;
    }
  } catch (error) {
    console.error("获取预填信息失败:", error);
  }
};

/**
 * @description 根据ID获取地址详情
 * @param {number} addressId
 */
const fetchAddressDetail = async (addressId) => {
  try {
    // [关键] 您的文档缺少“获取单个地址详情”的接口，这里假设一个
    const data = await request({
      url: `/my/addresses/${addressId}`,
      method: 'GET',
    });
    // 填充表单
    form.id = data.addressId;
    form.name = data.addressLinkman;
    form.phone = data.addressPhone;
    form.area = data.addressArea;
    form.details = data.addressDetail;
  } catch (error) {
    console.error("获取地址详情失败:", error);
  }
};

/**
 * @description 保存地址（新增或更新）
 */
const saveAddress = async () => {
  // 简单的前端校验
  if (!form.name || !form.phone || !form.area || !form.details) {
    return uni.showToast({ title: '请填写完整的地址信息', icon: 'none' });
  }

  uni.showLoading({ title: '保存中...' });
  
  try {
    let url, method, params;
		const userId = uni.getStorageSync('userId');
    // 构造请求参数
    params = {
			userId: userId,
      addressLinkman: form.name,
      addressPhone: form.phone,
      addressArea: form.area,
      addressDetail: form.details,
      addressIsExist: 1 // 假设 1 代表有效地址
    };

    if (isEditMode.value) {
      // 更新模式
      // [关键] 您的文档缺少更新接口，这里假设一个
      url = `/my/addresses/${form.id}`;
      method = 'PUT'; // RESTful风格用PUT更新
    } else {
      // 新增模式
      url = '/my/addAddresses';
      method = 'POST';
    }

    await request({ url, method, data: params });
    
    uni.hideLoading();
    uni.showToast({ title: '保存成功', icon: 'success' });
    setTimeout(() => uni.navigateBack(), 1500);

  } catch (error) {
    uni.hideLoading();
    console.error("保存地址失败:", error);
  }
};


// --- Lifecycle ---
onLoad((options) => {
  if (options.id) { // 编辑模式
    isEditMode.value = true;
    pageTitle.value = '编辑地址';
    fetchAddressDetail(options.id);
  } else { // 新增模式
    isEditMode.value = false;
    pageTitle.value = '新增地址';
    fetchUserInfoForForm();
  }
  uni.setNavigationBarTitle({ title: pageTitle.value });
});
</script>

    

<style lang="scss" scoped>
.address-form-page {
  background-color: $uni-bg-color-white;
  padding: 0 30rpx;
  min-height: 100vh;
}

.form-group {
  display: flex;
  align-items: flex-start;
  padding: 30rpx 10rpx;
  border-bottom: 1px solid $uni-border-color;
  
  .label {
    font-size: 32rpx;
    width: 180rpx;
    flex-shrink: 0;
    padding-top: 4rpx;
  }
  
  .input-field {
    flex-grow: 1;
    border: none;
    outline: none;
    font-size: 32rpx;
    
    &.textarea-field {
        min-height: 120rpx;
        line-height: 1.6;
    }
  }
}

.save-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: linear-gradient(135deg, $uni-primary, $uni-accent);
  color: white;
  border-radius: 45rpx;
  font-size: 32rpx;
  font-weight: 500;
  margin-top: 60rpx;
}
</style>